import argparse
import os
from app import create_app, db
from app.models import User


def init_db(admin: bool = True) -> None:
	app = create_app(os.getenv("FLASK_ENV"))
	with app.app_context():
		db.create_all()
		if admin:
			admin_username = os.getenv("ADMIN_USERNAME")
			admin_email = os.getenv("ADMIN_EMAIL")
			admin_password = os.getenv("ADMIN_PASSWORD")
			if admin_username and admin_email and admin_password:
				if not User.query.filter_by(email=admin_email).first():
					user = User.bootstrap_admin_from_env(admin_username, admin_email, admin_password)
					db.session.add(user)
					db.session.commit()


def run_server(host: str = "0.0.0.0", port: int = 5000, env: str = None) -> None:
	app = create_app(env or os.getenv("FLASK_ENV"))
	app.run(host=host, port=port, debug=app.config.get("DEBUG", False))


def main():
	parser = argparse.ArgumentParser(description="RBAC API 管理入口")
	parser.add_argument("command", choices=["init", "run"], help="init: 初始化数据库; run: 启动服务")
	parser.add_argument("--env", dest="env", default=os.getenv("FLASK_ENV", "development"))
	parser.add_argument("--host", dest="host", default="0.0.0.0")
	parser.add_argument("--port", dest="port", type=int, default=int(os.getenv("PORT", "5000")))
	args = parser.parse_args()

	if args.command == "init":
		init_db(admin=True)
		print("数据库已初始化")
	elif args.command == "run":
		run_server(host=args.host, port=args.port, env=args.env)


if __name__ == "__main__":
	main()


